//using code from file facedetect in examples from the book Learning OpenCV

#define CV_NO_BACKWARD_COMPATIBILITY

#include "cv.h"
#include "highgui.h"

#include <iostream>
#include <cstdio>

#include "faceDetector.h"

#ifdef _EiC
#define WIN32
#endif

using namespace std;
using namespace cv;

FaceDetector::FaceDetector(double scale=1.0) {
	
	this->scale = scale;
	
	cascadeName =
	"../resources/haarcascades/haarcascade_frontalface_alt.xml";
	//TODO : Make resource tracker (Singleton?)
	
	//TODO: Should throw exception instead?
	if( !cascade.load( cascadeName ) )
	{
		cerr << "ERROR: Could not load classifier cascade" << endl;
		cerr << "Usage: facedetect [--cascade=\"<cascade_path>\"]\n"
		"   [--nested-cascade[=\"nested_cascade_path\"]]\n"
		"   [--scale[=<image scale>\n"
		"   [filename|camera_index]\n" ;
	}
	
}

vector<Rect> *
FaceDetector::detectFace( const Mat& img
								 //,
								 // CascadeClassifier& cascade, //generated in class
								 // CascadeClassifier& nestedCascade, //not an option ATM
								 // double scale //not an option ATM
								 ) {
	
	//FIX : handle null input
	
	
    double t = 0;
    vector<Rect>* faces = new vector<Rect>;
    Mat gray, smallImg( cvRound (img.rows/scale), cvRound(img.cols/scale), CV_8UC1 );
    cvtColor( img, gray, CV_BGR2GRAY );
    resize( gray, smallImg, smallImg.size(), 0, 0, INTER_LINEAR );
    equalizeHist( smallImg, smallImg );
	
    t = (double)cvGetTickCount();
	
	//FIX : how does inputting faces work?
    cascade.detectMultiScale( smallImg, *faces,
							 1.1, 2, 0
							 //|CV_HAAR_FIND_BIGGEST_OBJECT
							 //|CV_HAAR_DO_ROUGH_SEARCH
							 |CV_HAAR_SCALE_IMAGE
							 ,
							 Size(30, 30) );
    t = (double)cvGetTickCount() - t;
    printf( "detection time = %g ms\n", t/((double)cvGetTickFrequency()*1000.) );
	
	return faces;
}
	








